package com.boomshake.service.impl;

import com.alibaba.fastjson2.JSON;
import com.boomshake.dto.AdminLoginRequest;
import com.boomshake.entity.AdminUser;
import com.boomshake.mapper.AdminUserMapper;
import com.boomshake.service.AdminUserService;
import com.boomshake.utils.JwtUtil;
import com.boomshake.utils.PasswordUtil;
import com.boomshake.vo.AdminLoginResponseVO;
import com.boomshake.vo.AdminUserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 管理员用户Service实现类
 *
 * @author BoomShake
 * @date 2024-12-15
 */
@Slf4j
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminLoginResponseVO login(AdminLoginRequest request, String clientIp) {
        log.info("管理员登录请求: username={}, ip={}", request.getUsername(), clientIp);

        // 根据用户名查询管理员
        AdminUser adminUser = getByUsername(request.getUsername());
        if (adminUser == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 验证密码
        if (!checkPassword(request.getPassword(), adminUser.getPassword())) {
            log.warn("管理员登录密码错误: username={}, ip={}", request.getUsername(), clientIp);
            throw new RuntimeException("用户名或密码错误");
        }

        // 检查账户状态
        if (adminUser.getStatus() != 1) {
            throw new RuntimeException("账户已被禁用");
        }

        // 更新最后登录信息
        adminUserMapper.updateLastLoginInfo(adminUser.getId(), LocalDateTime.now(), clientIp);

        // 生成JWT token
        String token = jwtUtil.generateToken(adminUser.getId(), adminUser.getUsername());

        // 构建响应
        AdminLoginResponseVO response = new AdminLoginResponseVO();
        response.setToken(token);

        AdminLoginResponseVO.AdminInfo adminInfo = new AdminLoginResponseVO.AdminInfo();
        adminInfo.setId(adminUser.getId());
        adminInfo.setUsername(adminUser.getUsername());
        adminInfo.setRealName(adminUser.getRealName());
        adminInfo.setAvatar(adminUser.getAvatar());
        adminInfo.setRole(adminUser.getRole());
        adminInfo.setLastLoginAt(adminUser.getLastLoginAt());

        // 解析权限和门店ID
        adminInfo.setPermissions(parseJsonArray(adminUser.getPermissions()));
        adminInfo.setStoreIds(parseJsonLongArray(adminUser.getStoreIds()));

        response.setAdminInfo(adminInfo);

        log.info("管理员登录成功: username={}, id={}", request.getUsername(), adminUser.getId());
        return response;
    }

    @Override
    public AdminUser getByUsername(String username) {
        return adminUserMapper.selectByUsername(username);
    }

    @Override
    public AdminUserInfoVO getAdminUserInfo(Long adminId) {
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser == null) {
            throw new RuntimeException("管理员不存在");
        }

        AdminUserInfoVO userInfo = new AdminUserInfoVO();
        BeanUtils.copyProperties(adminUser, userInfo);

        // 解析权限和门店ID
        userInfo.setPermissions(parseJsonArray(adminUser.getPermissions()));
        userInfo.setStoreIds(parseJsonLongArray(adminUser.getStoreIds()));

        return userInfo;
    }

    @Override
    public boolean checkPassword(String rawPassword, String encodedPassword) {
        return PasswordUtil.matches(rawPassword, encodedPassword);
    }

    /**
     * 解析JSON字符串数组
     */
    private List<String> parseJsonArray(String jsonStr) {
        if (StringUtils.hasText(jsonStr)) {
            try {
                return JSON.parseArray(jsonStr, String.class);
            } catch (Exception e) {
                log.warn("解析JSON字符串数组失败: {}", jsonStr, e);
            }
        }
        return null;
    }

    /**
     * 解析JSON长整型数组
     */
    private List<Long> parseJsonLongArray(String jsonStr) {
        if (StringUtils.hasText(jsonStr)) {
            try {
                return JSON.parseArray(jsonStr, Long.class);
            } catch (Exception e) {
                log.warn("解析JSON长整型数组失败: {}", jsonStr, e);
            }
        }
        return null;
    }
} 